package com.tomcat.myapplication.http;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import com.tomcat.myapplication.http.i_http.HttpProgressCancelListener;

import dmax.dialog.SpotsDialog;


/**
 * 处理ProgressDialog发送消息
 *
 */

public class HttpProgressDialogHandler extends Handler {

    public static final int SHOW_PROGRESS_DIALOG = 1;
    public static final int DISMISS_PROGRESS_DIALOG = 2;

    private SpotsDialog pd;
    private Context context;
    private boolean cancelable;
    private boolean show;  //这 参数 就是开启 true  还是不开起 flase
    private HttpProgressCancelListener mHttpProgressCancelListener;

    public HttpProgressDialogHandler(Context context, HttpProgressCancelListener mHttpProgressCancelListener,
                                     boolean cancelable, boolean show) {
        super();
        this.context = context;
        this.mHttpProgressCancelListener = mHttpProgressCancelListener;
        this.cancelable = cancelable;
        this.show = show;
    }

    /**
     * 初始化ProgressDialog
     */
    private void initProgressDialog() {
        if (pd == null) {
            pd = new SpotsDialog(context);
            pd.setCancelable(cancelable);
            if (cancelable) {
                pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {
                        mHttpProgressCancelListener.onCancelProgress();
                    }
                });
            }

            if (!pd.isShowing() && show) {
                pd.show();
            }
        }
    }

    /**
     * 隐藏ProgressDialog
     */
    private void dismissProgressDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
    }

    /**
     * 处理ProgressDialog存放的消息
     */
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SHOW_PROGRESS_DIALOG:
                initProgressDialog();
                break;
            case DISMISS_PROGRESS_DIALOG:
                dismissProgressDialog();
                break;
        }
    }
}
